const { db, genid } = require('../database/index')

const categoryHandle = {
  // 查询分类
  async categorySelect(req, res) {
    let sqlSelectStr = `SELECT * FROM categories`;
    const out = await db.async(sqlSelectStr);
    if (out.err) return res.jgcl(out.err, 500);

    res.jgcl('分类查询成功！', 200, out);
  },
  // 添加分类
  async categoryAdd(req, res) {
    
    const { name } = req.body;

    let sqlInsertSty = `INSERT INTO 
                      categories 
                      VALUES (${genid.NextId()},'${name}')`;

    const out = await db.async(sqlInsertSty);
    if (out.err) return res.jgcl(out.err, 500);

    res.jgcl('分类添加成功！', 200);
  },
  // 修改分类
  async categoryUpdate(req, res) {

    const { id, name } = req.body;
    console.log(req.body)
    let sqlUpdateStr = `UPDATE 
            categories 
            set 
            name = '${name}' 
            WHERE id = ${id}`;
    const out = await db.async(sqlUpdateStr);
    if (out.err) return res.jgcl(out.err, 500);

    res.jgcl('分类更新成功！', 200);
  },
  // 删除分类
  async categoryDelete(req, res) {

    const id = req.body.id

    let sqlDeleteStr = `DELETE FROM 
                categories 
                WHERE id = ${id}`;

    const out = await db.async(sqlDeleteStr);
    if (out.err) return res.jgcl(out.err, 500);

    res.jgcl('分类删除成功！', 200)
  }
}

module.exports = categoryHandle